package com.along.study.common;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class CustomMsgEncoder extends MessageToByteEncoder<CustomMsg> {

    public CustomMsgEncoder() {

    }

    @Override
    protected void encode(ChannelHandlerContext ctx, CustomMsg msg, ByteBuf out) throws Exception {
        //1个字节的传输类型，1个无意义字节（填充），4个字节的正文长度，10个字节的消息来源，10个字节的消息目的地，总长度是26个字节，26个字节后的数据才是内容
        int bodyLength = 26;
        if (msg.getData() != null) {
            bodyLength += msg.getData().length;
        }

        out.writeInt(bodyLength);

        out.writeByte(msg.getType());
        //没有意义，主要是为了填充字节（保证字节长度是2的整数倍）
        out.writeByte(0xff);

        out.writeBytes(msg.getFrom());

        out.writeBytes(msg.getTo());

        if (msg.getData() != null) {
            out.writeBytes(msg.getData());
        }
    }
}